package com.rcloud.server.sealtalk.controller;


import cn.hutool.core.lang.Snowflake;
import com.rcloud.server.sealtalk.constant.ErrorCode;
import com.rcloud.server.sealtalk.controller.param.PayOrderParam;
import com.rcloud.server.sealtalk.domain.PayOrder;
import com.rcloud.server.sealtalk.exception.ServiceException;
import com.rcloud.server.sealtalk.model.response.APIResult;
import com.rcloud.server.sealtalk.model.response.APIResultWrap;
import com.rcloud.server.sealtalk.service.PayOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 用户支付订单表
 *
 * @author zc
 * @email ${email}
 * @date 2019-11-01 16:58:58
 */
@RestController
@RequestMapping("/pay/order")
@Api(tags = "生成支付订单接口")
public class PayOrderController extends BaseController {
    @Autowired
    private PayOrderService payOrderService;

    @Autowired
    private Snowflake snowflake;

    /**
     * 用户生成支付订单的接口
     *
     * @param payOrderDto 支付订单相关参数
     * @return
     */

    @PostMapping("/insertPayOrder")
    @ApiOperation(value = "用户生成支付订单的接口")
    public APIResult<Object> insertPayOrder(@RequestBody PayOrderParam payOrderDto) throws ServiceException {
        Integer userId = getCurrentUserId();
        // 支付单号
        String payNo = "TN" + snowflake.nextId();
        //业务类型
        if (payOrderDto.getBusiType() == 1) {
            PayOrder payOrder = PayOrder.builder().build();
            payOrder.setBusiType(payOrderDto.getBusiType());
            payOrder.setCreateTime(new Date());
            payOrder.setOutTradeNo(payNo);
            payOrder.setUserId(userId);
            //充值
            if (payOrderDto.getBusiType() == 1) {
                payOrder.setTradeAmount(payOrderDto.getTradeAmount());
            }
            payOrder.setTradeStatus(0);
            payOrder.setVersion(1);
            payOrderService.saveSelective(payOrder);
        } else {
            throw new ServiceException(ErrorCode.NO_BUSI_TYPE);
        }
        return APIResultWrap.ok(payNo);
    }
}
